package ch.bluepenguin.jcr.groovy.tests;

import javax.jcr.Repository   
import javax.jcr.Session
import org.apache.jackrabbit.core.TransientRepository
import javax.jcr.SimpleCredentials;
import javax.jcr.Node
import ch.bluepenguin.jcr.groovy.builder.JcrBuilder
import ch.bluepenguin.jcr.groovy.builder.JcrSchemaBuilder

class JcrBuilderTests extends GroovyTestCase {
    static Session session

    static {
      synchronized(JcrBuilderTests.class) {
        if(!session) {
          Repository repository = new TransientRepository()
          //Session session = repository.login()
          session = repository.login(
                    new SimpleCredentials("username", "password".toCharArray()))
        }
      }
	}

	void testSimple() {
        JcrBuilder builder = new JcrBuilder()
        builder.session = session
        try {
            def node = builder.blog('title':'The Depressed') {
                entry() {
                    first('title': 'Monday again') {
                        attachment('nt:file') {
                            'jcr:content'('nt:resource',
                                ['jcr:mimeType':'text/plain',
                                 'jcr:data': 'Monday morning ...again',
                                 'jcr:lastModified': Calendar.instance])
                        }
                    }
                }
            }
            println "node:  ${node.name}"
            assert session.rootNode.getNode('blog').
                getProperty('title').string=='The Depressed'
            assert session.rootNode.getNode('blog/entry/first/attachment').primaryNodeType.name == 'nt:file'
        }finally {
            session.rootNode.getNode('blog').remove()
            session.save()
            
        }
	}

	void testBlueprint() {
        JcrSchemaBuilder builder = new JcrSchemaBuilder()
        builder.session = session
        try {
            def node = builder.blueprint() {
                master1(['name':'String',
                       'type':'String']) {
                    detail() 
                }
                master2(){
                    references('otherMaster':'../master1')
                }
            }
            session.save()
            builder.build({})
            //println builder.log
            assert session.rootNode.getNode('blueprint/master1').
                getProperty('name').string=='String'
            assert session.rootNode.getNode('blueprint/master2').
                getProperty('otherMaster').getNode() ==session.rootNode.getNode('blueprint/master1')
        }finally {
            session.rootNode.getNode('blueprint').remove()
            session.save()

        }

    }

}
